<template>

  <body>
  <!--  消息框-->
  <div v-if="operate=='checkInfo'" style="width: 100%;">
    <div style="width: 100%" v-if="selectedUser.userId!=undefined">
      <van-nav-bar ref="headNav" :title="selectedUser.userName" left-text="返回"
                   @click-left="back"
                   @click-right="operate='userChatRightTop'"
                   fixed left-arrow>
        <template #right>
          <van-icon name="bars" size="18"/>
        </template>
      </van-nav-bar>
      <van-pull-refresh v-model="messageIsLoading" :disabled="messageLoadingDisable" @refresh="onRefreshMessage">
        <!--        updated-->
        <div id="show_infos" ref="show_chat_info" :style="{height: (windowHeight-100)+'px'}"
             style="width: 100%;min-height:30rem;overflow-y: scroll;padding-top: 3rem;background-color: #eaeaea;">

          <div v-for="message in friendMessageMap.get(selectedUser.userId)">
            <div v-if="selectedUser.userId==message.fromUser" class="chat-sender">
              <div><img @click.stop="showUserInfo(selectedUser)"
                        :src="$store.getters.getAvatarBaseUrl+selectedUser.avatarPath"></div>
              <div>{{getName(message.fromUser)}}</div>
              <div style="width: auto;max-width: 200px;min-width: 0px">
                <div class="chat-left_triangle"></div>
                <span>{{message.msg}}</span>
              </div>
            </div>
<!--            <div class="chat-notice">-->
<!--              <span>{{message.date|formatDate("yyyy-MM-dd HH:mm:ss")}}</span>-->
<!--            </div>-->
            <!-- Right -->
            <div v-if="currentUser.userId!=message.toUser" class="chat-receiver">
              <div><img @click.stop="showUserInfo(currentUser)"
                        :src="$store.getters.getAvatarBaseUrl+currentUser.avatarPath"></div>
              <div>{{currentUser.userName}}</div>
              <div style="width: auto;max-width: 200px">
                <div class="chat-right_triangle"></div>
                <span>{{message.msg}}</span>
              </div>
            </div>
          </div>


        </div>
      </van-pull-refresh>
      <div style="width: 100%;height: 3rem;position: fixed;bottom: 0;background-color: white;">
        <van-field
          v-model="messageValue"
          rows="1"
          autosize
          type="textarea"
          placeholder="请输入消息"
          style="width: 79%;float: left"
          @keyup.enter.native="sendMessage(1)"
        />
        <van-button style="float: left" @click="sendMessage(1)" round type="info">发送</van-button>
      </div>
    </div>


    <div style="width: 100%" v-if="selectedGroup.eid!=undefined">
      <van-nav-bar :title="selectedGroup.groupName" left-text="返回"
                   @click-left="back"
                   @click-right="checkGroupMer"
                   fixed left-arrow>
        <template #right>
          <van-icon name="ellipsis" size="18"/>
        </template>
      </van-nav-bar>
      <!--        updated-->
      <van-pull-refresh v-model="groupMessageIsLoading" :disabled="groupMessageLoadingDisable" @refresh="onRefreshGroupMessage">
      <div id="groupChatDiv" :style="{height: (windowHeight-100)+'px'}"
           style="width: 100%;overflow-y: scroll;padding-top: 3rem;background-color: #eaeaea">
        <div v-for="message in selectedGroup.messages">
          <div v-if="message.fromUser!=currentUser.userId" class="chat-sender">
            <div><img @click.stop="showUserInfo(getUserInGroup(selectedGroup.userList,message.fromUser))"
                      :src="$store.getters.getAvatarBaseUrl+getUserInGroup(selectedGroup.userList,message.fromUser).avatarPath">
            </div>
            <div>{{getUserInGroup(selectedGroup.userList,message.fromUser).userName}}</div>
            <div style="width: auto;max-width: 200px;min-width: 0px">
              <div class="chat-left_triangle"></div>
              <span>{{message.msg}}</span>
            </div>
          </div>
<!--                    <div class="chat-notice">-->
<!--                      <span>{{message.date|formatDate("yyyy-MM-dd hh:mm:ss")}}</span>-->
<!--                    </div>-->
          <!-- Right -->
          <div v-if="message.fromUser==currentUser.userId" class="chat-receiver">
            <div><img @click.stop="showUserInfo(currentUser)"
                      :src="$store.getters.getAvatarBaseUrl+currentUser.avatarPath"></div>
            <div>{{currentUser.userName}}</div>
            <div style="width: auto;max-width: 200px">
              <div class="chat-right_triangle"></div>
              <span>{{message.msg}}</span>
            </div>
          </div>
        </div>

      </div>
      </van-pull-refresh>
      <div style="width: 100%;bottom: 0px;height: 3rem;position: fixed;background-color: white;">
        <van-field
          v-model="messageValue"
          rows="1"
          autosize
          type="textarea"
          placeholder="请输入消息"
          style="width: 79%;float: left"
          @keyup.enter.native="sendMessage(0)"
        />
        <van-button style="float: left" @click="sendMessage(0)" round type="info">发送</van-button>
      </div>
    </div>

  </div>

  <!--    聊天右上角点击页面-->
  <div v-if="operate=='userChatRightTop'">
    <van-nav-bar left-text="返回"
                 @click-left="operate='checkInfo'"
                 fixed left-arrow>
    </van-nav-bar>
  </div>


  <div v-if="operate=='checkGroupMer'" style="width: 100%;">
    <van-nav-bar left-text="返回"
                 @click-left="operate='checkInfo'"
                 title="群内用户"
                 @click-right="inviteFriendsDialog=true"
                 fixed left-arrow>
      <template #right>
        <van-icon name="plus" size="18"/>
      </template>
    </van-nav-bar>
    <div style="width: 200px;height: 32px">
      <el-dialog
        :visible.sync="inviteFriendsDialog"
        title="邀请新好友"
        width="80%"
      >
        <el-checkbox-group v-model="inviteFriendsList">
          <el-checkbox v-for="(user,index) in friendList" v-if="!isInGroup(user,selectedGroup.userList)"
                       :label="user.userId" :key="index">{{user.userName}}
          </el-checkbox>
        </el-checkbox-group>

        <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="inviteFriendsGroups()">邀请好友</el-button>
         </span>
      </el-dialog>
    </div>
    <ul style="list-style: none;height: 550px;padding: 0px;margin: 20px 0px 0px;">
      <li style="margin: 0px;cursor: pointer;width: 180px;height: 40px" v-for="user in selectedGroup.userList"
          @click="showUserInfo(user)">
        <el-avatar style="float: left" shape="square" size="medium"
                   :src="$store.getters.getAvatarBaseUrl+user.avatarPath"></el-avatar>
        <span style="float: left;margin-left: 7px">{{user.userName}}</span>
        <el-badge style="float: left" v-if="user.unreadNum!=0" :value="user.unreadNum" :max="99" class="item">
        </el-badge>
      </li>
    </ul>
  </div>

  <!--修改密码-->
  <van-dialog v-model="changePasswordShow" title="修改密码" width="80%" style="padding-bottom: 30px"
              :show-confirm-button="false">
    <van-form :model="changePassword" @submit="changePasswordfun">
      <van-field
        v-model="changePassword.oldPassword"
        name="旧密码"
        type="password"
        label="旧密码"
        placeholder="旧密码"
        :rules="[{ required: true, message: '请填写旧密码' },{validator:validatorOldPassword,message: '原密码输入错误'}]"
      />
      <van-field
        v-model="changePassword.newPassword"
        type="password"
        name="新密码"
        label="新密码"
        placeholder="新密码"
        :rules="[{ required: true, message: '请填写新密码' }]"
      />
      <van-field
        v-model="changePassword.secondPassword"
        type="password"
        name="确认新密码"
        label="确认新密码"
        placeholder="请再次输入新密码"
        :rules="[{ required: true, message: '请再次填写新密码' },{ validator, message: '两次输入的密码不同' }]"
      />
      <div style="margin: 16px 16px 40px;">
        <van-button round block type="info" style="width: 50%;float: left" native-type="submit">修改密码</van-button>
        <van-button round block type="info" style="width: 50%;float: left"
                    @click="changePassword={},changePasswordShow=false" native-type="button">取消
        </van-button>
      </div>
    </van-form>
  </van-dialog>



  <!--    用户信息展示-->
  <van-dialog v-model="userInfoShow" show-cancel-button>
    <van-image
      width="8rem"
      height="8rem"
      fit="contain"
      round
      :src="$store.getters.getAvatarBaseUrl+showUser.avatarPath"
    />
    <van-field label="用户名" :value="showUser.userName" readonly/>
    <van-field label="用户ID" :value="showUser.userId" readonly/>
    <van-field label="生日" :value="showUser.birthday|formatDate('yyyy-MM-dd')" readonly/>
  </van-dialog>
<!--修改群头像-->
  <van-dialog v-model="groupInfoShow" show-cancel-button>
    <van-uploader v-model="fileGroupAvatar" multiple :max-count="1" :disabled="currentUser.userId!=showGroup.lord" :after-read="uploadGroupAvatar"/>
    <van-field label="群名" :value="showGroup.groupName" readonly/>
    <van-field label="群主ID" :value="showGroup.lord" readonly/>
  </van-dialog>

  <div v-if="operate=='mainHome'" style="width: 100%;height: 100%">
    <van-nav-bar style="background-color: #73b9ff;" fixed left-arrow>
      <template #left>
        <el-avatar @click.native="dialogVisible2=true"
                   :src="$store.getters.getAvatarBaseUrl+currentUser.avatarPath">
        </el-avatar>
      </template>
      <template #right>
        <van-popover
          v-model="showPopover"
          trigger="click"
          :actions="actions"
          @select="onSelect"
          placement="bottom-end"
        >
          <template #reference>
            <van-icon name="plus" size="18"/>
          </template>
        </van-popover>

      </template>


    </van-nav-bar>


    <el-dialog
      :visible.sync="addUserDialog"
      title="创建群聊"
      width="80%"
    >
      <el-checkbox-group v-model="checkedUsers">
        <el-checkbox v-for="(user,index) in friendList" :label="user.userId" :key="index">{{user.userName}}
        </el-checkbox>
      </el-checkbox-group>

      <span slot="footer" class="dialog-footer">
             <el-input placeholder="请输入群聊名" style="margin-bottom: 10px" @keyup.enter.native="createGroup()"
                       v-model="createGroupChatName"></el-input>
         <el-button type="primary" @click="createGroup()">创建群聊</el-button>
         </span>
    </el-dialog>


    <el-dialog title="修改信息"
               :visible.sync="dialogVisible2"
               width="80%">
      <el-form id="changeInfo" :model="upLoadUser" status-icon :rules="rules" ref="uploadForm" class="demo-ruleForm">
        <el-form-item>
          <el-upload
            ref="upload"
            action="#"
            :auto-upload="false"
            :on-preview="handleBeforeUpload"
            :on-change="handleChange"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-avatar @click.native="dialogVisible2 = true" shape="square" size="medium" :src="headerPic"></el-avatar>
          </el-upload>
        </el-form-item>


        <el-form-item prop="userId">
          <el-input type="text" disabled v-model="upLoadUser.userId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="userName">
          <el-input type="text" v-model="upLoadUser.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="birthday">
          <el-date-picker
            v-model="upLoadUser.birthday"
            align="right"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('uploadForm')">提交</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>


    <div class="chat_list_box">
      <van-search
        v-model="searchInfo"
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        @search="addFriend()"
      >
        <template #action>
          <div @click="addFriend">搜索</div>
        </template>
      </van-search>
      <van-pull-refresh v-model="isLoading"  @refresh="onRefresh">
        <!--        <处理消息-->
        <div v-if="active==0" style="width: 100%;height: auto;min-height: 20rem;">
          <van-cell-group>
            <van-swipe-cell v-for="(reqRecord,key) in reqRecordList" :key="key">
              <van-cell :border="false" :title="reqRecord.fromUser" :label="reqRecord.content"
                        :value="reqRecord.date|formatDate('MM.dd HH:mm')"/>
              <template #right>
                <van-button @click="handelRequest('agree',reqRecord)" square type="primary" text="同意"/>
                <van-button @click="handelRequest('refuse',reqRecord)" square type="danger" text="拒绝"/>
              </template>
            </van-swipe-cell>
          </van-cell-group>
        </div>
      </van-pull-refresh>
      <van-pull-refresh v-model="isLoading" :disabled="userRefreshDisabled" @refresh="onRefresh">
        <!--联系人-->
        <div v-if="active==1" style="width: 100%;height: auto;min-height: 20rem;">
          <van-tabs @click="changeSelect()" v-model="activeContact" style="margin-top: 1rem">
            <van-tab title="好友">
              <van-cell-group id="userList" ref="userList" style="margin-bottom: 4rem;min-height: 34rem">
                <van-swipe-cell v-for="(user,key) in friendListMap.values()" :key="key">
                  <van-cell @click="selectUser(user)" >
                    <template #icon>
                      <el-avatar @click.native.stop="showUserInfo(user)"
                                 style="float: left;margin-right: 1rem;margin-left: 1rem" shape="square" size="medium"
                                 :src="$store.getters.getAvatarBaseUrl+user.avatarPath"></el-avatar>
                    </template>
                    <template #title>
                      <span class="custom-title">{{user.userName}}</span>
                    </template>
                    <template #right-icon>
                      <el-badge style="float: left" v-show="user.unreadNum!=0" :value="user.unreadNum" :max="99"
                                class="item">
                      </el-badge>
                    </template>
                    <template #label>
                      <span>{{user.status}}</span>
                    </template>
                  </van-cell>
                  <template #right>
                    <van-button square text="删除" type="danger" @click="deleteFriend(user)" class="delete-button"/>
                  </template>
                </van-swipe-cell>
              </van-cell-group>
            </van-tab>

            <van-tab title="群聊">
              <van-cell-group id="groupList" ref="userList">
                <van-swipe-cell v-for="(group,key) in groupChatList" :key="key">
                  <van-cell @click="selectGroup(group)">
                    <template #icon>
                      <el-avatar @click.native.stop="showGroupInfo(group)" style="float: left;margin-right: 1rem;margin-left: 1rem" shape="square" size="medium"
                                 :src="$store.getters.getAvatarBaseUrl+group.avatarPath"></el-avatar>
                    </template>
                    <template #title>
                      <span class="custom-title">{{group.groupName}}</span>
                    </template>
                    <template #right-icon>
                      <div v-if="group.lord==currentUser.userId"
                           style="width: 10px;height: 10px;background-color: #94ef94;;float: right;border-radius: 10px;margin-top: 0.6rem;position: absolute;right: 25px"></div>
                    </template>
                  </van-cell>
                  <template #right>
                    <van-button v-if="currentUser.userId!=group.lord" square text="退出群聊" type="danger"
                                @click="exitGroupChat(group)" class="delete-button"/>
                    <van-button v-if="currentUser.userId==group.lord" square text="删除" type="danger"
                                @click="deleteGroupChat(group)" class="delete-button"/>
                  </template>
                </van-swipe-cell>
              </van-cell-group>

            </van-tab>
          </van-tabs>
        </div>
      </van-pull-refresh>
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <!--    动态-->
        <div v-if="active==2" style="width: 100%;height: auto;min-height: 20rem;text-align: left">
          <mt-index-list>
            <mt-index-section index="A">
              <mt-cell title="Aaron"></mt-cell>
              <mt-cell title="Alden"></mt-cell>
              <mt-cell title="Austin"></mt-cell>
            </mt-index-section>
            <mt-index-section index="B">
              <mt-cell title="Baldwin"></mt-cell>
              <mt-cell title="Braden"></mt-cell>
            </mt-index-section>

            <mt-index-section index="Z">
              <mt-cell title="Zack"></mt-cell>
              <mt-cell title="Zane"></mt-cell>
            </mt-index-section>
          </mt-index-list>
        </div>
      </van-pull-refresh>
      <van-tabbar v-model="active">
        <van-tabbar-item icon="chat-o" :badge="reqRecordList.length">消息</van-tabbar-item>
        <van-tabbar-item icon="friends-o">联系人</van-tabbar-item>
        <van-tabbar-item icon="setting-o">动态</van-tabbar-item>
      </van-tabbar>

    </div>
  </div>
  </body>

</template>

<script>
  import http from '../utils/http'
  import {getFriends} from '@/api/user'
  import {Dialog} from 'vant'
  import {Notify} from 'vant';

  export default {
    //添加update方法：
    // updated: function () {
    //   this.$nextTick(function () {
    //     var div = document.getElementById('show_infos');
    //     var test = document.getElementById('groupChatDiv');
    //     if (div != null) {
    //       div.scrollTop = div.scrollHeight;
    //     }
    //     if (test != null) {
    //       test.scrollTop = test.scrollHeight;
    //     }
    //   })
    // },
    data() {
      var check = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }
        return callback();
      };

      return {
        showGroup:{},
        fileGroupAvatar:[],
        //一对一消息刷新
        messageIsLoading: false,
        messageLoadingDisable:false,
        messageListScroll: 0,
        //群聊刷新
        groupMessageLoadingDisable:false,
        groupMessageIsLoading:false,
        groupMessageListScroll: 0,
        //用户信息页面下拉刷新
        userRefreshDisabled:false,
        userListScroll:0,
        groupListScroll:0,
        //展示用户信息
        userInfoShow: false,
        //群消息信息及换头像
        groupInfoShow:false,
        showUser: {},

        //修改密码弹窗
        changePasswordShow: false,
        changePassword: {
          oldPassword: "",
          newPassword: "",
          secondPassword: '',
        },


        windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
        windowHeight: document.documentElement.clientHeight, //实时屏幕高度
        isLoading: false,
        checkGroupUser: false,
        operate: "mainHome",
        checkInfoBox: false,
        active: 0,
        activeContact: 0,
        searchValue: '',
        icon: {
          active: 'https://img01.yzcdn.cn/vant/user-active.png',
          inactive: 'https://img01.yzcdn.cn/vant/user-inactive.png',
        },
        showPopover: false,
        // 通过 actions 属性来定义菜单选项-->
        actions: [{text: '创建群聊'}, {text: '添加好友'}, {text: '修改密码'}, {text: '退出登陆'}],
        selectIndex: 0,
        clickIcon: 'chat_info',
        headerPic: '',
        websocket: null, // WebSocket对象
        messageValue: '', // 消息内容
        friendList: [], //用户信息

        selectedUser: {},
        selectedGroup: {},
        currentUser: this.$store.getters.getUser,
        friendMessageMap: new Map(),
        friendListMap: new Map(),
        searchInfo: '',
        //所有群聊
        groupChatList: [],
        //添加好友弹唱窗口
        addUserDialog: false,
        checkedUsers: [],
        createGroupChatName: '',
        reqRecordList: [],

        dialogVisible2: false,//弹窗
        dialogVisible: false,
        file: {},
        inviteFriendsDialog: false,
        inviteFriendsList: [],
        upLoadUser: this.$store.getters.getUser,
        rules: {
          userName: [
            {validator: check, trigger: 'blur'}
          ],
          userId: [
            {validator: check, trigger: 'blur'}
          ],
          birthday: [
            {validator: check, trigger: 'blur'}
          ]
        },

      }
    },
    watch: {
      messageListScroll(val) {
        if (val == 0) {
          this.messageLoadingDisable = false
        } else {
          this.messageLoadingDisable = true
        }
      },
      groupMessageListScroll(val){
        if (val == 0) {
          this.groupMessageLoadingDisable = false
        } else {
          this.groupMessageLoadingDisable = true
        }
      },
      active(val){
        if(val==1){
          let userListBox=document.getElementById('userList')
          if(userListBox!=null){
            userListBox.addEventListener('scroll',()=>{
              this.userListScroll=userListBox.scrollTop;
              // console.log(this.userListScroll)
            })
          }
        }
      },
      userListScroll(val){
        if (val == 0) {
          this.userRefreshDisabled = false
        } else {
          this.userRefreshDisabled = true
        }
      }
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          window.fullWidth = document.documentElement.clientWidth;
          this.windowHeight = window.fullHeight; // 高
          this.windowWidth = window.fullWidth; // 宽
          // console.log("实时屏幕高度：", this.windowHeight);
          // console.log("实时屏幕宽度：", this.windowWidth);
        })()
      };
      // this.$nextTick(function () {
      //   var div = this.$refs.show_chat_info
      //   if(div!=null) {
      //     console.log(123)
      //     div.addEventListener('click', event => {
      //       this.messageListScroll = div.scrollTop;
      //     });
      //   }
      // })

    },
    created() {
      // console.log("实时屏幕高度：", this.windowHeight);
      // console.log("实时屏幕宽度：", this.windowWidth);
      this.connectWebSocket();
      this.getFriends();
      this.getAllReqRecord();
      this.headerPic = this.$store.getters.getAvatarBaseUrl + this.currentUser.avatarPath

    },
    methods: {
      showGroupInfo(group){
        this.groupInfoShow=true;
        this.showGroup=group;
      },
      //展示用户信息弹框
      showUserInfo(user) {
        this.showUser = user;
        this.userInfoShow = true;
      },
      //删除群聊
      deleteGroupChat(group) {
        Dialog.confirm({
          message: '你确定删除群聊吗',
        })
          .then(() => {
            // on confirm
            http.get('groupChat/deleteGroupChat',{groupId:group.eid}).then((res) =>{
              if(res.data.code==200){
                Notify({ type: 'success', message: res.data.message });
                this.deleteGroup(group)
              }else{
                Notify({ type: 'danger', message: res.data.message });
              }
            })
          })
          .catch(() => {
            // on cancel
            // 警告通知
            Notify({ type: 'warning', message: '取消操作' });
          });
      },
      deleteGroup(group){
        this.groupChatList.splice(this.groupChatList.indexOf(group),1)
      },
      //退出群聊
      exitGroupChat(group) {
        Dialog.confirm({
          message: '你确定退出群聊吗？',
        })
          .then(() => {
            // on confirm
            http.get('/groupChat/exitGroupChat', {
              userId: this.currentUser.userId,
              groupId: group.eid
            }).then((response) => {
              if (response.data.code == 200) {
                // 成功通知
                Notify({type: 'success', message: response.data.message});
                this.deleteGroup(group)
              } else {
                // 危险通知
                Notify({type: 'danger', message: response.data.message});
                ;
              }
            })
          })
          .catch(() => {
            // on cancel
            Notify({type: 'warning', message: '你已经取消操作'});
          });
      },
      //删除好友
      deleteFriend(user) {
        Dialog.confirm({
          message: '你确定删除好友吗？',
        })
          .then(() => {
            // on confirm
            http.get("user/deleteFriend", {
              userId: this.currentUser.userId,
              friendId: user.userId,
            }).then((res) => {
              if (res.data.code == 200) {
                // 成功通知
                // console.log('deleteFriend')
                Notify({type: 'success', message: res.data.message});
                this.removeUser(user.userId)
                this.deleteUserInfoToSocket(user)
              } else {
                // 危险通知
                Notify({type: 'danger', message: res.data.message});
                ;
              }
            })
          })
          .catch(() => {
            // on cancel
            Notify({type: 'warning', message: '你已经取消操作'});
          });
      },
      //退出登陆
      loginOut() {
        Dialog.confirm({
          message: '你确定退出登陆吗？',
        })
          .then(() => {
            // on confirm
            this.$store.commit("REMOVE_INFO")
            window.localStorage.clear()
            this.websocket.close()
            this.$router.push("/login")
          })
          .catch(() => {
            // on cancel
            Notify({type: 'warning', message: '你已经取消操作'});
          });

      },
      //修改密码
      changePasswordfun() {
        http.get("user/changePassword", {
          newPassword: this.$md5(this.changePassword.newPassword),
          eid: this.currentUser.eid
        }).then((res) => {
          if (res.data.code = 200) {
            this.$message.success(res.data.message);
            this.changePassword = {}
            this.changePasswordShow = false
            this.loginOut();
          } else {
            this.$message.success(res.data.message);
          }
        })
      },
      validatorOldPassword(val) {
        // console.log(this.currentUser)
        // console.log(val)
        // let old=this.changePassword.oldPassword
        if (this.$md5(val) == this.currentUser.password) {
          return true;
        } else {
          return false;
        }
      },
      validator(val) {
        if (this.changePassword.newPassword == this.changePassword.secondPassword) {
          return true;
        } else {
          return false;
        }
      },
      getReqRecordDate(date) {
        // FormatDate
      },
      onRefresh() {
        setTimeout(() => {
          this.getFriends();
          this.getAllReqRecord();
          this.getAllGroup();
          // this.$messages.success('刷新成功');
          this.isLoading = false;
        }, 1000);
      },
      onRefreshMessage() {
        setTimeout(() => {
          this.getMessage();
          this.messageIsLoading = false;
        }, 1000);
      },
      //下拉刷新群消息
      onRefreshGroupMessage(){
        setTimeout(() => {
          this.getAllGroup();
          this.groupMessageIsLoading = false;
        }, 2000);
      },
      back() {
        this.checkInfoBox = false
        this.operate = 'mainHome'
        this.selectedGroup ={}
        this.selectedUser={}
        this.messageIsLoading=true;
        this.groupMessageIsLoading=true;
      },
      checkGroupMer() {
        this.operate = 'checkGroupMer'

      },
      onSelect(action) {
        // console.log(action)
        if (action.text == '创建群聊') {
          this.addUserDialog = true
        }
        if (action.text == '修改密码') {
          this.changePasswordShow = true
        }
        if (action.text == '退出登陆') {
          this.loginOut();
        }
      },
      selectBox(index) {
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            http.post('/user/updateUser', this.upLoadUser).then((res) => {
              if (res.data.code == 200) {
                this.currentUser = this.upLoadUser
                this.uploadFile();
                this.dialogVisible2 = false
                this.$message.success(res.data.message)
              } else {
                this.$message.error(res.data.message)
              }
            })

          } else {
            return false;
          }
        });
      },
      //点击好友
      selectUser(user) {
        this.selectedGroup = {}
        this.selectedUser = user
        // if (this.friendMessageMap.get(user.userId).length == 0) {
        //   this.getMessage()
        // }
        this.operate = "checkInfo"

        // }
        if (this.friendListMap.get(user.userId).unreadNum != 0) {
          http.get('/message/readInfo', {
            userId: this.currentUser.userId,
            friendId: this.selectedUser.userId,
          }).then((res) => {
            //未读消息清空
            this.friendListMap.get(user.userId).unreadNum = 0
            this.$forceUpdate()
          })
        }
        this.selectedGroup = {}
        setTimeout(() => {
          this.updateScroll()
        }, 100);
        // //滑动条到最底部

      },
      getMessage() {
        http.get('/message/getMessageList', {
          userId: this.currentUser.userId,
          friendId: this.selectedUser.userId,
        }).then((res) => {
          //查询出所有朋友与当前联系人的聊天消息
          this.friendMessageMap.set(this.selectedUser.userId, res.data)
          this.$forceUpdate()
        })
      },
      removeUser(userId) {
        this.friendListMap.delete(userId);
        this.friendMessageMap.delete(userId);
        for (let i = 0; i < this.friendList.length; i++) {
          if (this.friendList[i].userId == userId) {
            this.$delete(this.friendList, i)
          }
        }
        this.$forceUpdate
      },
      getFriends() {
        getFriends({
          userId: this.currentUser.userId
        }).then((res) => {
          this.friendList = res.data
          for (var i = 0; i < res.data.length; i++) {
            this.friendListMap.set(res.data[i].userId, res.data[i])
            this.friendMessageMap.set(res.data[i].userId, [])
          }
          this.$forceUpdate()
        })
      },
      connectWebSocket() {

        if ('WebSocket' in window) {
          this.websocket = new WebSocket(
            'ws://localhost:8080/websocket/' + this.currentUser.userName + '/' + this.currentUser.userId
            //打包用
            // 'ws://8.136.254.73:8080/websocket/' + this.currentUser.userName + '/' + this.currentUser.userId
          )
        } else {
          alert('不支持建立socket连接')
        }
        //连接发生错误的回调方法
        this.websocket.onerror = function () {

        }
        //连接成功建立的回调方法
        this.websocket.onopen = function (event) {

        }
        //接收到消息的回调方法
        var that = this
        this.websocket.onmessage = function (event) {
          var object = eval('(' + event.data + ')')
          console.log(object)
          if (object.type == 0) {
            // 提示连接成功
            if (object.name != that.currentUser.userName) {
              that.$message.success("你的好友" + object.name + "上线了，快去找他(她)聊天吧！")
              that.changeStatus(object.userId,'在线')
            } else {
              that.$message.success("你已经上线，可以跟朋友聊天了")
            }
          }
          if (object.type == 1) {
            //显示消息
            let message = {
              fromUser: object.id,
              toUser: that.currentUser.userId,
              msg: object.msg,
              date: new Date()
            }
            if (that.selectedUser.userId == object.id) {
              message.status = "已读"
            } else {
              message.status = "未读"
            }
            that.friendMessageMap.get(message.fromUser).push(message)
            if (message.fromUser != that.selectedUser.userId) {
              that.friendListMap.get(message.fromUser).unreadNum += 1;
            }
            that.$forceUpdate()
            http.post("/message/addMessage", message)

          }
          if (object.type == 2) {
            for (let i = 0; i < that.groupChatList.length; i++) {
              if (that.groupChatList[i].eid == object.groupId) {
                let mes = {
                  msg: object.msg,
                  fromUser: object.id,
                  date: new Date(),
                  groupEid: object.groupId
                }
                that.groupChatList[i].messages.push(mes)
                break;
              }
            }
            that.$forceUpdate()
          }
          //收到请求
          if (object.type == 3) {
            that.reqRecordList.push(object.reqRecord)
            that.$forceUpdate()
          }
          //删除好友
          if (object.type == 4) {
            that.removeUser(object.id)
          }
          //某人同意请求
          if (object.type == 5) {
            that.getFriends()
            that.$message.success(object.name + "已同意你的好友请求")
          }
          //某人离线
          if(object.type==6){
            that.changeStatus(object.userId,"离线")
            that.$message.success(object.name+"已经离线了")
          }

          that.updateScroll()
        }
        //连接关闭的回调方法
        this.websocket.onclose = function () {

        }
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
          this.websocket.close()
        }
      },
      //更新滑动条
      updateScroll() {
        console.log("updateScroll")
        this.$nextTick(function () {
          var div = document.getElementById('show_infos');
          var test = document.getElementById('groupChatDiv');
          if (div != null) {
            div.scrollTop = div.scrollHeight;
            div.addEventListener('scroll', event => {
              this.messageListScroll = div.scrollTop;
              // console.log(this.messageListScroll)
            });
          }
          if (test != null) {
            test.scrollTop = test.scrollHeight;
            test.addEventListener('scroll', event => {
              this.groupMessageListScroll = test.scrollTop;
              console.log(this.groupMessageListScroll)
            });
          }
        })
      },
      //修改好友在线情况
      changeStatus(userId,status){
        for (let i = 0; i < this.friendList.length; i++) {
          if(this.friendList[i].userId == userId){
            this.friendList[i].status=status;
          }
        }
        this.$forceUpdate()
      },
      // 发送消息
      sendMessage: function (type) {

        if (this.messageValue == '') {
          this.$message.warning("请输入消息")
          return;
        }
        if (type == 1) {
          var socketMsg = {fromUser: this.currentUser, msg: this.messageValue, toUser: this.selectedUser}
          this.friendMessageMap.get(this.selectedUser.userId).push({
            fromUser: this.currentUser.userId,
            msg: this.messageValue,
            toUser: this.selectedUser.userId,
            date: new Date()
          })

          this.$forceUpdate()
          // if (this.aisle == "") {
          //   //群聊.
          //   socketMsg.type = 0;
          // } else {
          //单聊.
          socketMsg.type = 1
          // }
          this.websocket.send(JSON.stringify(socketMsg))
          this.messageValue = '';
          //群发
        } else if (type == 0) {
          var socketMsg = {fromUser: this.currentUser, msg: this.messageValue, groupId: this.selectedGroup.eid, type: 0}
          this.websocket.send(JSON.stringify(socketMsg))
          this.messageValue = '';
          //删除好友
        }
        this.updateScroll()
      },
      //向websocket说我删了好友
      deleteUserInfoToSocket(user) {
        var socketMsg = {fromUser: this.currentUser, toUser: user, type: 2}
        this.websocket.send(JSON.stringify(socketMsg))
      },
      getName(userId) {
        return this.friendListMap.get(userId).userName
      },
      getUserInGroup(userList, userId) {
        for (let i = 0; i < userList.length; i++) {
          if (userList[i].userId == userId) {
            return userList[i];
          }
        }
      },
      //向websocket锁我同意了某人的请求
      sendAgreeFriendReq(userId) {
        var socketMsg = {fromUser: this.currentUser, toUser: {userId: userId}, type: 3}
        this.websocket.send(JSON.stringify(socketMsg))
      },
      changeSelect() {
        // console.log(operate)
        // this.clickIcon = operate
        this.selectedUser = {}
        this.selectedGroup = {}
        this.$forceUpdate()
        if (this.activeContact == 1) {
          this.getAllGroup()
        }

        if (this.activeContact == 2) {
          this.getFriends();
        }
      },
      //查询当前用户所在的群
      getAllGroup() {
        http.get("/groupChat/getGroup", {
          userId: this.currentUser.userId
        }).then((response) => {
          this.groupChatList = response.data
        })
      },
      selectGroup(group) {
        this.selectedGroup = group
        this.selectedUser = {}
        this.operate = "checkInfo"
        this.$forceUpdate()
        //滑动条到最底部
        setTimeout(() => {
          this.updateScroll()
        }, 100);
      },
      createGroup() {
        if (this.createGroupChatName == '') {
          this.$message.warning("请输入群聊名再创建")
          return
        }
        let users = ''
        for (let i = 0; i < this.checkedUsers.length; i++) {
          users += this.checkedUsers[i] + ":"
        }
        let createGroupDto = {
          users: this.checkedUsers,
          createGroupName: this.createGroupChatName,
          lord: this.currentUser.userId
        }
        users = users.substring(0, users.length - 1)
        http.post('groupChat/createGroup', createGroupDto).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.message)
            this.addUserDialog = false
            this.checkedUsers.length=0;
            // console.log(this.checkedUsers)
            this.createGroupName = "";
            // if (this.clickIcon == 'groupChat') {
              this.getAllGroup()
            // }
          } else {
            this.$message.error(res.data.message)
          }
        })
      },
      inviteFriendsGroups() {
        let fd = new FormData();
        fd.append("userIdList", this.inviteFriendsList);
        fd.append("groupId", this.selectedGroup.eid);
        fd.append('currentUserId', this.currentUser.userId);
        fd.append('groupName', this.selectedGroup.groupName);
        http.post("groupChat/inviteFriends", fd).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.message)
            this.inviteFriendsDialog = false
            if (this.clickIcon == 'groupChat') {
              this.getAllGroup()
            }
          } else {
            this.$message.error(res.data.message)
          }
        })
      },
      isInGroup(user, userList) {
        for (let i = 0; i < userList.length; i++) {
          if (userList[i].userId == user.userId) {
            return true
          }
        }
        return false
      },
      getAllReqRecord() {
        http.get("user/getReqRecordById", {
          userId: this.currentUser.userId
        }).then((res) => {
          this.reqRecordList = res.data;
          this.$forceUpdate()
        })
      },
      dateFormat: function (date) {
        // return moment(date).format('YYYY-MM-DD hh:mm:ss')
        let _this = this
        date = new Date(date)
        let yy = date.getFullYear()
        let mm = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
        let dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        let hh = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        let mf = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        let ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss

      },
      handelRequest(type, reqRecord) {
        if (type == 'agree') {
          reqRecord.status = '已同意'
        } else {
          reqRecord.status = '已拒绝'
        }
        reqRecord.date = this.dateFormat(reqRecord.date)
        http.post('user/handleReqRecord', reqRecord).then((res) => {
          this.getAllReqRecord();
          if (res.data.code == 200) {
            this.$message.success(res.data.message);
            if (res.data.message == '已同意好友请求') {
              this.getFriends();
              this.sendAgreeFriendReq(reqRecord.fromUser)
            }
          } else {
            this.$message.error(res.data.message);
          }
        })

      },
      addFriend() {
        if (this.searchInfo == "") {
          this.$message.warning("你未输入好友ID")
          return
        }
        http.get('user/addFriend', {
          userId: this.currentUser.userId,
          friendId: this.searchInfo,
        }).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.message);
          } else if (res.data.code == 400) {
            this.$message.warning(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
          this.searchInfo = '';
        })
      },
      handleBeforeUpload(file) {
        if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
          this.$message({
            type: 'warning',
            message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
          })
        }
        let size = file.size / 1024 / 1024 / 2
        if (size > 2) {
          this.$message({
            type: 'warning',
            message: '图片大小必须小于2M'
          })
        }
        // this.file=file;
      },
      handleChange(file, fileList) {
        this.file = fileList[fileList.length - 1];
        //此处预览照片
        this.headerPic = URL.createObjectURL(this.file.raw);
      },
      uploadFile() {
        let fd = new FormData();//通过form数据格式来传
        let userId = this.currentUser.userId;
        fd.append("file", this.file.raw); //传文件
        fd.append('userId', userId)
        fd.append('groupId',0)
        this.dialogVisible = true;
        http.upload('/up/uploadHead', fd, {
          'Content-Type': 'multipart/form-data'
        }).then((res) => {
          http.get('user/getUserById', {
            userId: userId
          }).then((res) => {
            this.$store.commit('SET_USER', res.data);
            this.currentUser = res.data;
            this.headerPic = this.$store.getters.getAvatarBaseUrl + this.currentUser.avatarPath;
          })
        })

      },
      changeGroupAvatar(groupId,url){
        for (let i = 0; i < this.groupChatList.length; i++) {
          if(this.groupChatList[i].eid==groupId){
              this.groupChatList[i].avatarPath = url;
          }
        }
        this.$forceUpdate()
      },
      uploadGroupAvatar(){
        console.log(this.fileGroupAvatar)
        Dialog.confirm({
          message: '你确定上传头像吗？',
        })
          .then(() => {
            // on confirm
            let groupId=this.showGroup.eid
            let file=this.fileGroupAvatar[0]
            file.status = 'uploading';
            file.message = '上传中...';
            let fd = new FormData();//通过form数据格式来传
            fd.append("file", file.file); //传文件
            fd.append('groupId', groupId)
            http.upload('/up/uploadHead', fd, {
              'Content-Type': 'multipart/form-data'
            }).then((res) => {
              if(res.data.code==200) {
                file.status = 'success';
                file.message = '';
                this.changeGroupAvatar(groupId,res.data.data)
              }else{
                file.status = 'failed';
                file.message = '上传失败';
              }
            }).catch((error) => {
              file.status = 'failed';
              file.message = '上传失败';
            })
          })
          .catch(() => {
            // on cancel
            Notify({type: 'warning', message: '你已经取消操作'});
          });

      },
      handleAvatarSuccess(res, file) {
        this.headerPic = URL.createObjectURL(file.raw);
      },
    }
  }
</script>

<style scoped>
  .chat_list_box {
    width: 100%;
    margin-top: 3rem;
  }

  .chatBox_header {
    width: 180px;
    height: 30px;
  }

  .chatBox_header .el-input__inner {
    width: 140px !important;
    height: 30px !important;
  }

  .chatBox_header .el-input__prefix {
    top: -5px !important;
  }

  #changeInfo .el-date-editor {
    width: 100% !important;
  }

  .active {
    background-color: #dbdbda !important;
  }

  .chat-sender {
    clear: both;
    font-size: 80%;
    float: left;
  }

  .chat-sender div:nth-of-type(1) {
    float: left;
  }

  .chat-sender div:nth-of-type(2) {
    margin: 0 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: left;
  }

  .chat-sender div:nth-of-type(3) {
    background-color: white;
    /*float: left;*/
    margin: 0 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius: 7px;
    text-indent: -12px;
  }

  .chat-receiver {
    clear: both;
    font-size: 80%;
    float: right;
  }

  .chat-receiver div:nth-of-type(1) {
    float: right;
  }

  .chat-receiver div:nth-of-type(2) {
    margin: 0px 50px 2px 50px;
    padding: 0px;
    color: #848484;
    font-size: 70%;
    text-align: right;
  }

  .chat-receiver div:nth-of-type(3) {
    /*float:right;*/
    background-color: #b2e281;
    margin: 0px 50px 10px 50px;
    padding: 10px 10px 10px 10px;
    border-radius: 7px;
  }

  .chat-receiver div:first-child img,
  .chat-sender div:first-child img {
    width: 40px;
    height: 40px;
    /*border-radius: 10%;*/
  }

  .chat-left_triangle {
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent white transparent transparent;
    position: relative;
    left: -22px;
    top: 3px;
  }

  .chat-right_triangle {
    height: 0px;
    width: 0px;
    border-width: 6px;
    border-style: solid;
    border-color: transparent transparent transparent #b2e281;
    position: relative;
    right: -22px;
    top: 3px;
  }

  .chat-notice {
    clear: both;
    font-size: 70%;
    color: white;
    text-align: center;
    margin-top: 15px;
    margin-bottom: 15px;
  }

  .chat-notice span {
    background-color: #cecece;
    line-height: 25px;
    border-radius: 5px;
    padding: 5px 10px;
  }

  #userList .van-cell__title {
    width: auto;
    max-width: 100px;
    text-align: left;
  }

  #groupList .van-cell__title {
    width: auto;
    max-width: 100px;
    text-align: left;
  }
</style>
